<template>
  <div :class="{ 'avue--collapse': isCollapse }" class="avue-contail">
    <div class="avue-header">
      <!-- 顶部导航栏 -->
      <!-- <top /> -->
    </div>

    <div class="avue-layout">
      <div class="avue-left">
        <!-- 左侧导航栏 -->
        <sidebar />
      </div>
      <div class="avue-main">
        <!-- 顶部标签卡 -->
        <tags />
        <!-- 主体视图层 -->
        <div
          style="height: calc(100% - 60px); overflow-y: auto; overflow-x: hidden"
          id="avue-view"
        >
          <keep-alive>
            <router-view class="avue-view" v-if="$route.meta.keepAlive" />
          </keep-alive>
          <router-view class="avue-view" v-if="!$route.meta.keepAlive" />
        </div>
      </div>
    </div>
    <div class="avue-shade" @click="showCollapse" />
    <!--    全局电话接单-->
    <!-- <orders v-if="showRepair" /> -->
    <!-- 全局自动打印 -->
    <!-- <auto-print
      ref="autoprint"
      :printType="printType"
      :lock="autoPrintFlag"
      v-if="autoPrintFlag"
    ></auto-print> -->
    <!-- 提示音 -->
    <audio
      preload="auto"
      style="display: none"
      ref="audio"
      src="/audio/ding-dong.mp3"
      controls="controls"
    ></audio>
    <!-- <edit-password ref="ep"></edit-password> -->
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import tags from "./tags";
import top from "./top/";
import sidebar from "./sidebar/";
import admin from "@/util/admin";
import { getStore } from "@/util/store.js";
import eventBus from '@/util/eventBus'
import * as SockJS from "sockjs-client";
import Stomp from "stomp-websocket";
import store from "@/store";
import { getSysmsginner } from "@/api/admin/user";
// import orders from "@/views/repair/orders/index.vue";
// import autoPrint from "@/views/canteen/ordermanage/autoPrint";
// import editPassword from "@/components/editPassword/index";
export default {
  name: "Index",
  provide() {
    return {
      Index: this,
    };
  },
  components: {
    top,
    tags,
    sidebar,
    // orders,
    // editPassword,
    // autoPrint,
  },
  data() {
    return {
      // 刷新token锁
      refreshLock: false,
      num: 0,
      // 刷新token的时间
      refreshTime: "",
      // 计时器
      timer: "",
    };
  },
  created() {
    // 实时检测刷新token
    this.refreshToken();
  },
  destroyed() {
    clearInterval(this.refreshTime);
    clearInterval(this.timer);
    /*
     * 默认关闭websocket，如需工作流通知，则开启
     * this.disconnect()
     */
  },
  mounted() {
    this.init();
    /*
     * 默认关闭websocket，如需工作流通知，则开启
     * this.initWebSocket()
     */
    // this.initWebSocket();
    this.getSysmsginnerNum();
    if (this.shouldEdit) {
      this.$refs.ep.openDialog();
    }
    this.setFontSize()
    window.addEventListener('resize', e => { 
      this.setFontSize()
    }, false);
  },
  beforeDestroy() {
    window.removeEventListener('resize', e => { 
      this.setFontSize()
    });
  },
  watch: {
    shouldEdit: {
      immediate: true,
      handler(val) {
        if (val) {
        }
      },
    },
    isCollapse() {
      this.setFontSize()
    }
  },
  computed: {
    ...mapGetters([
      "userInfo",
      "isLock",
      "isCollapse",
      "website",
      "expires_in",
      "unreadMessage",
      "autoRefreshFlag",
    ]),
    ...mapState({
      showRepair: (state) => state.common.showRepair,
      autoPrintFlag: (state) => state.canteen.autoPrintFlag,
      printType: (state) => state.canteen.printType,
      shouldEdit: (state) => state.common.shouldEdit,
    }),
  },
  methods: {
    setFontSize() {
      var Width = window.innerWidth//浏览器窗口的内部宽度（包括滚动条）
        
      || document.documentElement.clientWidth
        
      || document.body.clientWidth;
      let fsize
      if (this.isCollapse) {
        fsize = (Width - 100)/88.575
      } else {
        fsize = (Width - 240)/88.575
      }
      document.getElementsByTagName('html')[0].style.fontSize = fsize + 'px'
    },
    getSysmsginnerNum() {
      getSysmsginner({ readStatus: 2 }).then((res) => {
        let unreadMessage = res.data.data.total;
        this.$store.commit("SET_MESSAGE", unreadMessage);
      });
    },
    showCollapse() {
      this.$store.commit("SET_COLLAPSE");
    },
    openMenu(item = {}) {
      this.$store
        .dispatch("GetMenu", { type: true, id: item.id })
        .then((data) => {
          if (data.length !== 0) {
            this.$router.$avueRouter.formatRoutes(data, true);
          }
        });
    },
    // 屏幕检测
    init() {
      this.$store.commit("SET_SCREEN", admin.getScreen());
      window.onresize = () => {
        setTimeout(() => {
          this.$store.commit("SET_SCREEN", admin.getScreen());
        }, 0);
      };
    },
    // 实时检测刷新token
    refreshToken() {
      this.refreshTime = setInterval(() => {
        const token = getStore({
          name: "access_token",
          debug: true,
        });
        if (this.validatenull(token)) {
          return;
        }
        if (this.expires_in <= 1000 && !this.refreshLock) {
          this.refreshLock = true;
          this.$store.dispatch("RefreshToken").catch(() => {
            clearInterval(this.refreshTime);
          });
          this.refreshLock = false;
        }
        this.$store.commit("SET_EXPIRES_IN", this.expires_in - 10);
      }, 10000);
    },
    initWebSocket() {
      this.connection();
      const self = this;
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          self.stompClient.send("test");
        } catch (err) {
          console.log("断线了: " + err);
          self.disconnect();
          self.connection();
        }
      }, 5000);
    },
    connection() {
      const token = store.getters.access_token;
      const TENANT_ID = getStore({ name: "tenantId" })
        ? getStore({ name: "tenantId" })
        : "1";
      const headers = {
        Authorization: "Bearer " + token,
      };
      // 建立连接对象
      this.socket = new SockJS('/act/ws')// 连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
      // this.socket = new SockJS("/admin/ws");
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket);
      this.stompClient.debug = null;
      // 向服务器发起websocket连接
      this.stompClient.connect(
        headers,
        () => {
          let target = `/msg/${TENANT_ID}/${this.userInfo.username}/remind`
          // console.log(target);
         this.stompClient.subscribe(target,
            (msg) => {
              // console.log(msg);
              // 订阅服务端提供的某个topic;
              this.getSysmsginnerNum();
              // if (this.autoRefreshFlag && msg.body == 2) {
              //   this.$store.dispatch("setSocketFlag", true);
              // }
              this.$refs.audio.play();
              this.$notify({
                title: "消息提醒",
                type: "warning",
                dangerouslyUseHTMLString: true,
                message: "您有一个新消息，请及时查收！",
                offset: 60,
              });
            }
          );
          this.stompClient.subscribe("/topic", (msg) => {
            console.log(msg)
            this.num += 1
            if (msg && msg.body === 'salon') {
              this.$store.commit("SET_SALON", this.num);
              // eventBus.$emit('isSalon')
            }
            if (msg && msg.body === 'physical') {
              // this.$store.commit("SET_PHYSICAL", true);
              eventBus.$emit('isPhysical')
            }
            
          });
        },
        (err) => {}
      );
    },
    disconnect() {
      if (this.stompClient != null) {
        this.stompClient.disconnect();
        console.log("Disconnected");
      }
    },
  },
};
</script>
